package com.cherrish.demo.register;

import com.cherrish.demo.framework.URL;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author cherrish
 * @time 2019-03-20 15:44
 * @name Register
 * @desc:
 */
public class Register {
    private static Map<String, Map<URL, Class>> REGISTER = new HashMap<>(8);
    public static void register(URL url, String interfaceName, Class implClass){
        Map<URL, Class> map = new HashMap<>(1);
        map.put(url, implClass);
        REGISTER.put(interfaceName, map);
        saveFile();
    }

    public static Class get(URL url, String interfaceName){
        return REGISTER.get(interfaceName).get(url);
    }
    public static URL random(String interfaceName){
        REGISTER = getFile();
        return REGISTER.get(interfaceName).keySet().iterator().next();
    }

    private static void saveFile(){
        try {
            FileOutputStream fileOutputStream = new FileOutputStream("/var/rpc/temp.txt");
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
            objectOutputStream.writeObject(REGISTER);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static Map<String, Map<URL, Class>> getFile(){
        try {
            FileInputStream fileOutputStream = new FileInputStream("/var/rpc/temp.txt");
            ObjectInputStream objectInputStream = new ObjectInputStream(fileOutputStream);
            return  (Map<String, Map<URL, Class>>) objectInputStream.readObject();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
